package com.ruoyi.eqmonitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.eqmonitor.dispose.service.MqttService;
import com.ruoyi.eqmonitor.domain.BzDataEntity;
import com.ruoyi.eqmonitor.domain.BzIpEntity;
import com.ruoyi.eqmonitor.service.IBzDataService;
import com.ruoyi.eqmonitor.service.IBzIpService;
import cn.hutool.json.JSONArray;
import lombok.NonNull;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("bz")
public class BzController {
    @Resource
    private IBzDataService bzDataService;
    @Resource
    private IBzIpService bzIpService;
    @GetMapping("list")
    public AjaxResult list(){
        List<BzIpEntity> list = bzIpService.list();
        list.forEach(bzIpEntity -> {
            JSONArray array = bzDataService.getDataByIp(bzIpEntity.getIp());
            if (array == null) {
                bzIpEntity.setData(new JSONObject());
                return;
            }
            List<cn.hutool.json.JSONObject> jsonObjects1 =array.stream().map(a->(cn.hutool.json.JSONObject)a).filter(b->b.getStr("parameterKey").equals("DB142,DD720")).collect(Collectors.toList());
            List<cn.hutool.json.JSONObject> jsonObjects2 =array.stream().map(a->(cn.hutool.json.JSONObject)a).filter(b->b.getStr("parameterKey").equals("DB142,DD724")).collect(Collectors.toList());
            JSONObject data = new JSONObject();
            data.put("level", jsonObjects1.isEmpty()?null:jsonObjects1.get(0).get("parameterValue"));
            data.put("speed", jsonObjects2.isEmpty()?null:jsonObjects2.get(0).get("parameterValue"));
            bzIpEntity.setData(data);
        });
        return AjaxResult.success(list);
    }
    @GetMapping("getDataByIp")
    public AjaxResult getDataByIp(String ip){

        return AjaxResult.success(bzDataService.getDataByIp(ip));
    }


    @PostMapping("saveData")
    public AjaxResult saveData(@RequestBody BzDataEntity bzDataEntity){
        return AjaxResult.success(bzDataService.save(bzDataEntity));
    }
    @Resource
    private MqttService mqttService;
    @PostMapping("mqtt")
    public AjaxResult mqtt(@RequestBody com.alibaba.fastjson2.JSONObject jsonObject){
        String snCode = jsonObject.getString("snCode");
        com.alibaba.fastjson2.JSONObject payload = jsonObject.getJSONObject("payload");
        String topic = String.format("%s/%s/Set", "SysPara", snCode);
        System.err.println(topic);
        System.err.println(payload);
        mqttService.publish(topic, JSONObject.toJSONString(payload).getBytes());
        return AjaxResult.success();
    }


}
